using Microsoft.Extensions.Logging;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Infrastructure.Data;

namespace SumerCoreDevOps.Infrastructure.GitTrigger;

/// <summary>
/// Git 触发规则管理器
/// </summary>
public class GitTriggerRuleManager
{
    private readonly FreeSQLProvider _dbProvider;
    private readonly ILogger<GitTriggerRuleManager> _logger;

    public GitTriggerRuleManager(FreeSQLProvider dbProvider, ILogger<GitTriggerRuleManager> logger)
    {
        _dbProvider = dbProvider;
        _logger = logger;
    }

    /// <summary>
    /// 创建触发规则
    /// </summary>
    public async Task<GitTriggerRule> CreateRuleAsync(
        long workflowId,
        string name,
        string triggerType,
        string? branchPattern,
        string? tagPattern,
        string? pathFilter,
        string? createdBy)
    {
        var rule = new GitTriggerRule
        {
            WorkflowId = workflowId,
            Name = name,
            TriggerType = triggerType,
            BranchPattern = branchPattern,
            TagPattern = tagPattern,
            PathFilter = pathFilter,
            CreatedBy = createdBy,
            CreatedAt = DateTime.UtcNow,
            IsEnabled = true
        };

        await _dbProvider.Orm.Insert(rule).ExecuteAffrowsAsync();
        _logger.LogInformation("创建 Git 触发规则: {Name}, 工作流 ID: {WorkflowId}", name, workflowId);

        return rule;
    }

    /// <summary>
    /// 更新触发规则
    /// </summary>
    public async Task UpdateRuleAsync(
        long id,
        string name,
        string triggerType,
        string? branchPattern,
        string? tagPattern,
        string? pathFilter,
        bool isEnabled)
    {
        var rule = await _dbProvider.Orm.Select<GitTriggerRule>()
            .Where(r => r.Id == id)
            .FirstAsync();

        if (rule == null)
        {
            throw new InvalidOperationException($"触发规则 {id} 不存在");
        }

        rule.Name = name;
        rule.TriggerType = triggerType;
        rule.BranchPattern = branchPattern;
        rule.TagPattern = tagPattern;
        rule.PathFilter = pathFilter;
        rule.IsEnabled = isEnabled;
        rule.UpdatedAt = DateTime.UtcNow;

        await _dbProvider.Orm.Update<GitTriggerRule>()
            .SetSource(rule)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("更新 Git 触发规则: {Id}", id);
    }

    /// <summary>
    /// 删除触发规则
    /// </summary>
    public async Task DeleteRuleAsync(long id)
    {
        await _dbProvider.Orm.Delete<GitTriggerRule>()
            .Where(r => r.Id == id)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("删除 Git 触发规则: {Id}", id);
    }

    /// <summary>
    /// 根据工作流 ID 获取所有触发规则
    /// </summary>
    public async Task<List<GitTriggerRule>> GetRulesByWorkflowIdAsync(long workflowId)
    {
        return await _dbProvider.Orm.Select<GitTriggerRule>()
            .Where(r => r.WorkflowId == workflowId)
            .OrderBy(r => r.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 根据 ID 获取触发规则
    /// </summary>
    public async Task<GitTriggerRule?> GetRuleByIdAsync(long id)
    {
        return await _dbProvider.Orm.Select<GitTriggerRule>()
            .Where(r => r.Id == id)
            .FirstAsync();
    }

    /// <summary>
    /// 检查是否应该触发工作流
    /// </summary>
    public async Task<bool> ShouldTriggerWorkflowAsync(
        long workflowId,
        string triggerType,
        string? branchName = null,
        string? tagName = null,
        List<string>? changedPaths = null)
    {
        var rules = await _dbProvider.Orm.Select<GitTriggerRule>()
            .Where(r => r.WorkflowId == workflowId && r.IsEnabled && r.TriggerType == triggerType)
            .ToListAsync();

        foreach (var rule in rules)
        {
            // 检查分支匹配
            if (!string.IsNullOrEmpty(rule.BranchPattern) && !string.IsNullOrEmpty(branchName))
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(branchName, rule.BranchPattern))
                {
                    continue;
                }
            }

            // 检查 Tag 匹配
            if (!string.IsNullOrEmpty(rule.TagPattern) && !string.IsNullOrEmpty(tagName))
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(tagName, rule.TagPattern))
                {
                    continue;
                }
            }

            // 检查路径过滤
            if (!string.IsNullOrEmpty(rule.PathFilter) && changedPaths != null && changedPaths.Any())
            {
                var patterns = rule.PathFilter.Split(',', StringSplitOptions.RemoveEmptyEntries)
                    .Select(p => p.Trim())
                    .ToList();

                var hasMatch = changedPaths.Any(path =>
                    patterns.Any(pattern => IsPathMatch(path, pattern)));

                if (!hasMatch)
                {
                    continue;
                }
            }

            // 如果所有条件都匹配，则应该触发
            return true;
        }

        return false;
    }

    /// <summary>
    /// 简单的路径匹配（支持通配符）
    /// </summary>
    private bool IsPathMatch(string path, string pattern)
    {
        // 简化版通配符匹配
        if (pattern.Contains("**"))
        {
            pattern = pattern.Replace("**", ".*");
        }
        else if (pattern.Contains("*"))
        {
            pattern = pattern.Replace("*", "[^/]*");
        }

        return System.Text.RegularExpressions.Regex.IsMatch(path, $"^{pattern}$");
    }
}
